import React, { Component } from 'react'
import { connect, ConnectedProps } from "react-redux";
import { Button, Input, message, Spin, Table } from "antd";
import recoverDeviceModal from "./RecoverDeviceModal";
import { getRes } from "../../../../../configFile";
import { listDeletedDevice, queryDeletedDeviceAmount, searchDeletedDevice } from "../../../../../requests/Device";
import Device from "../../../../../types/Device";
import ButtonGroup from "antd/lib/button/button-group";
import { RootState } from "../../../../../reducers";
import moment from 'moment';

// @ts-ignore
interface PropsFromRedux extends ConnectedProps<typeof connector> { }
interface IState {
    DeviceSource: Array<Device & { key: number }>       //显示信息
    amount: number                                                          //总共条目
    offset: number                                                          //偏移量
    limit: number                                                           //条数
    isLoading: boolean                                                       //是否加载中
    modifyModalVisible: boolean,                                             //编辑的模态框是否为显示状态
    isSearch: boolean
}
const { Search } = Input;
class DeletedDeviceList extends Component<PropsFromRedux, IState> {
    constructor(props: PropsFromRedux) {
        super(props)
        this.state = {
            DeviceSource: [],
            amount: 0,
            offset: 0,
            limit: 10,
            isLoading: true,
            modifyModalVisible: false,
            isSearch: false
        }
    }


    //恢复设备
    recoverDevice = (deviceID: number, deviceName: string, refresh: () => void) => {
        recoverDeviceModal(deviceID, deviceName, refresh)
    }

    //获取已删除设备信息
    getDevice = async () => {
        try {
            this.setState({
                ...this.state,
                isLoading: true
            })

            const amountRes = getRes(await queryDeletedDeviceAmount())
            const res = getRes(await listDeletedDevice(this.state.offset, this.state.limit))
            if (res.isSuccessful && amountRes.isSuccessful) {
                this.setState({
                    DeviceSource: res.data.map((item: Device) => Object.assign({}, item, { key: item.deviceID })),
                    amount: amountRes.data
                })
            } else {
                console.error(res);
                console.error(amountRes);
                message.error("查询失败")
            }
        }
        catch (error) {
            message.error(error.toString())
        }
        finally {
            this.setState({
                ...this.state,
                isLoading: false
            })
        }
    }

    componentDidMount() {
        this.getDevice()
    }

    columns = [{
        title: '设备名称',
        dataIndex: 'deviceName',
        key: 'deviceName',
    },
    {
        title: '创建时间',
        dataIndex: 'creationTime',
        key: 'creationTime',
        render: (record: number) => {
            return moment(record).format('YYYY-MM-DD')
        }
    },

    {
        title: '操作',
        key: 'action',
        render: (record: Device) => (
            <ButtonGroup>
                <Button size='middle' danger onClick={this.recoverDevice.bind(this, record.deviceID, record.deviceName, this.getDevice)}>恢复</Button>
            </ButtonGroup>
        )
    }]

    onSearch: (values: string) => void = async values => {
        console.log(values)
        try {
            const res = getRes(await searchDeletedDevice(values))
            if (!res.isSuccessful) {
                console.error(res);
                message.error("查询失败")
            }
            this.setState({ DeviceSource: res.data, amount: res.data.length, isSearch: true })
        } catch (err) {
            message.error(JSON.stringify(err))
        }
    }

    render() {
        return (
            <div>
                <Spin spinning={this.state.isLoading}>
                    <Search placeholder="搜索" onSearch={values => this.onSearch(values)} enterButton />
                    <Table columns={this.columns}
                        dataSource={this.state.DeviceSource}
                        pagination={{
                            onChange: this.state.isSearch ? undefined : (page, pageSize) => {
                                console.log(page, pageSize);
                                if (!!pageSize) {
                                    this.setState({
                                        offset: (page - 1) * (pageSize),
                                        limit: (pageSize)
                                    }, () => {
                                        this.getDevice()
                                    })
                                } else {
                                    console.error('pageSize == undefined')
                                }
                            },
                            defaultPageSize: this.state.limit,
                            total: this.state.amount,
                            showSizeChanger: false
                        }} />
                </Spin>
            </div>
        )
    }
}

const mapStateToProps = (state: RootState) => {
    return {
        userID: state.loginReducers.userID
    }
}

const connector = connect(mapStateToProps)
export default connector(DeletedDeviceList)